﻿using csharp_books_415.Data;
using csharp_books_415.Data.Models;
using csharp_books_415.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace csharp_books_415.Adapters
{
    public class BookDataAdapter : IBooksAdapter
    {
        // Gets all books
        public List<Book> GetBooks()
        {
            using (BooksDbContext db = new BooksDbContext())
            {
                return db.Books.ToList();
               
            }
        }
        // get details for one book
        public Book GetBook(int bid)
        {
            using (BooksDbContext db = new BooksDbContext())
            {
                // temp instance TEMP BOOK
                Book tB = db.Books
                    .Include("Reviews")
                    .Include("Author")
                    .FirstOrDefault(b => b.BookId == bid);
                return tB;
            }
        }




        public void AddBook(BookCreateVm nBook)
        {
            using (BooksDbContext db = new BooksDbContext())
            {
                db.Books.Add(nBook.Book);
                db.SaveChanges();
                
            }

        }


        public void DeleteBook(int bid)
        {
            using (BooksDbContext db = new BooksDbContext())
            {
                Book tB = db.Books.FirstOrDefault(b => b.BookId == bid);
                db.Books.Remove(tB);
                db.SaveChanges();
            }
            
        }


        public void SaveBook(BooksEditVm eVm )
        {
            using (BooksDbContext db = new BooksDbContext())
            {
                // get book by ID
                Book tB = db.Books.FirstOrDefault(b => b.BookId == eVm.Book.BookId);
                // apply the changes
                tB.AuthorId = eVm.Book.AuthorId;
                tB.IsBestSeller = eVm.Book.IsBestSeller;
                tB.PageCount = eVm.Book.PageCount;
                tB.Published = eVm.Book.Published;
                tB.Title = eVm.Book.Title;
                // save changes to db
                db.SaveChanges();
            }

        }


    }
}